package cn.nawang.ebeim.client.process;

import java.util.concurrent.atomic.AtomicLongFieldUpdater;

/**
 * 进度条
 * Created by GanJc on 2016/1/20.
 */
public class ProcessBar {

    //总共传输文件数
    private int totalFileNum ;

    private long allBytes ;

    private static final AtomicLongFieldUpdater TRANSFER_BYTES_UPDATER =
            AtomicLongFieldUpdater.newUpdater(ProcessBar.class,"transferBytes");

    private volatile long transferBytes = 0 ;

    public ProcessBar() {
    }

    public ProcessBar(long allBytes) {
        this.allBytes = allBytes;
    }

    public void increaseRate(long increase){
        long oldValue = transferBytes ;
        long newValue = oldValue + increase ;
        while (!TRANSFER_BYTES_UPDATER.compareAndSet(this,oldValue,newValue)){
            oldValue = transferBytes ;
            newValue = oldValue + increase ;
        }
        transferBytes = newValue ;
    }

    public double getRate(){
        if(allBytes==0){
            return 100;
        }
        return transferBytes * 100 / allBytes ;
    }

    public long getAllBytes() {
        return allBytes;
    }

    public long getTransferBytes() {
        return transferBytes;
    }

    public void setAllBytes(long allBytes) {
        this.allBytes = allBytes;
    }

    public void setTransferBytes(long transferBytes) {
        this.transferBytes = transferBytes;
    }

    @Override
    public String toString() {
        return "{ allBytes=" + allBytes +
                ", transferBytes=" + transferBytes +" }" ;
    }
}
